﻿var brr=[];//web端菜单选择id组合
var appBrr=[];//APP端菜单选择id组合

$(function() {
    queryListRole(1);
    initWebTree();//web树菜单
    initAppTree();//app树菜单

});

////绑定点击事件
$("#btnAddRole").on("click", function () {
    //新增角色验证表单
    addRoleValidator();
    //情况表单和验证
    $("#modalAddRole :text").val("");
    $("#addRoleDescrebe").val("");
    $("#roleName")[0].readOnly=false;
    $(".tipArea div").html("").attr("class","");
    $("#oldRoleName").val("");
    $("#exampleModalLabel").text("新增角色");
    //web
    var treeObj = $.fn.zTree.getZTreeObj("treeOrg");//根据 treeId 获取 zTree 对象
    treeObj.checkAllNodes(false);//清空树状结构图
    //app
    var appTreeObj = $.fn.zTree.getZTreeObj("treeOrg2");//根据 treeId 获取 zTree 对象
    appTreeObj.checkAllNodes(false);//清空树状结构图
    $("#modalAddRole").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal');
});


//新增角色验证
function addRoleValidator(){
    $.formValidator.initConfig({
        formid: "frmMain", onerror: function (msg) {return false;}, onsuccess: function () {return true;}
    });

    $("#roleName").formValidator({
        onfocus: "请输入角色名称",
        oncorrect: " "
    }).InputValidator({
        min: 2,
        max: 20,
        onempty: "请输入角色名称",
        onerror: "角色名称长度为2到20个字符"
    }).RegexValidator({
        regexp: "illegal",
        datatype: "enum",
        onerror: "角色名称不能含有特殊字符"
    }).FunctionValidator({
        fun: function (val, elem) {
            var oldRoleName=$("#oldRoleName").val();
            if (val==oldRoleName) {
                return true;
            }
            else{
                var htmlObj= $.ajax({
                    type:"post",
                    url:"/cwp/front/sh/role!execute",
                    beforeSend:function(requests){
                        requests.setRequestHeader("platform", "pc");
                    },
                    async:false,
                    dataType: "json",
                    data:{
                        uid:"c009",
                        userId:localStorage.getItem("parkId"),
                        roleName:$("#roleName").val()
                    }
                });
                var result=JSON.parse(htmlObj.responseText);
                if (result.returnCode == "0") {
                    return true;
                } else {
                    return "该角色已经存在";
                }

            }
        }
    });

    $("#addRoleDescrebe").formValidator({
        onfocus: "请输入角色描述",
        oncorrect: " "
    }).InputValidator({
        min: 2,
        max: 20,
        onempty: "请输入角色描述",
        onerror: "角色描述长度为2到20个字符"
    }).RegexValidator({
        regexp: "illegal",
        datatype: "enum",
        onerror: "角色描述不能含有特殊字符"
    });
}

function editRoleValidator(){
    $.formValidator.initConfig({
        formid: "frmMain", onerror: function (msg) {return false;}, onsuccess: function () {return true;}
    });

    $("#roleName").unbind();

    $("#addRoleDescrebe").formValidator({
        onfocus: "请输入角色描述",
        oncorrect: " "
    }).InputValidator({
        min: 2,
        max: 20,
        onempty: "请输入角色描述",
        onerror: "角色描述长度为2到20个字符"
    }).RegexValidator({
        regexp: "illegal",
        datatype: "enum",
        onerror: "角色描述不能含有特殊字符"
    });
}


function queryListRole(pageIndex){
    $.getJSON('/cwp/src/json/role/role_c001.json',function(data){
        var loaderRoleTab = new LoaderTable("loaderRoleTab","roleTab","/cwp/front/sh/role!execute","uid=c001",pageIndex,10,roleResultArrived,"","frmSearch");
        loaderRoleTab.loadSuccessed(data);
    });
    // loaderRoleTab.Display();
}

//搜索角色列表
$("#btnSearchList").on("click",function(){
    //是否第一次加载
    isPostBack=true;
    queryListRole(1);
});

//回调函数 当前页
function paginationCallback(page_index){
    if(!isPostBack) {
        queryListRole(page_index+1);
    }
}

function roleResultArrived(result){
    var thead="<thead>"+
        "<tr>"+
        "<th>序列</th>"+
        "<th>角色名称</th>"+
        "<th>描述</th>"+
        "<th>操作</th>"+
        "</tr>"+
        "</thead>";
    var tbobys = "<tbody>";
    for(var i=0;i<result.beans.length;i++){
        var user = result.beans[i];
        tbobys+="<tr><td>"+parseInt(i+1)+"</td>"+
            "<td>"+user.roleName+"</td>"+
            "<td>"+user.describeRole+"</td>"+
            "<td><a class='t-btn t-btn-sm t-btn-blue t-btn-edit' onclick=updateRole('"+user.roleId+"')>修改</a></td>"+
            "</tr>"
    }
    tbobys += "</tbody>";
    //显示表格html
    $('#roleTab').html(thead+tbobys);
}


function saveMenu(){
    //判断表单验证是否通过
    zTreeOnClick();//WEB
    appZTreeOnClick();//APP
    if ($.formValidator.PageIsValid()) {
        var roleId=$('#hidRoleId').val();
        if(roleId==""||roleId==undefined){
            // PostForm("/cwp/front/sh/role!execute", "uid=c004&roleMenu=" + brr +"&appRoleMenu=" +appBrr, "", addMenuResultArrived, "","frmMain");
            $.getJSON('/cwp/src/json/role/role_c004.json',function(data){
                addMenuResultArrived(data);
            })
        }
        else{
            // PostForm("/cwp/front/sh/role!execute", "uid=c007&roleMenu=" + brr +"&appRoleMenu=" +appBrr,"", updateSuccessMenuResultArrived, '',"frmMain");
            $.getJSON('/cwp/src/json/role/role_c007.json',function(data){
                updateSuccessMenuResultArrived(data);
            })
        }
        //关闭模态框
        $("#modalAddRole").modal("hide");
    }
}
function updateSuccessMenuResultArrived(result){
    brr = [];
    appBrr = [];
    switch (result.returnCode) {
        case "0":
            tipModal("icon-checkmark", "修改成功");
            isPostBack=true;
            queryListRole(1);
            break;
        case "2":
            tipModal("icon-cross", "修改失败");
            break;
        case "-9999":
            tipModal("icon-cross", "修改失败");
            break;
        default:
            break;
    }
}
function addMenuResultArrived(result){
    brr = [];
    appBrr = [];
    switch (result.returnCode) {
        case "0":
            tipModal("icon-checkmark", "添加成功");
            isPostBack=true;
            queryListRole(1);
            break;
        case "2":
            tipModal("icon-cross", "添加失败");
            break;
        case "-9999":
            tipModal("icon-cross", "添加失败");
            break;
        default: break;
    }

}
//--------------------新增结束-----------------//

function updateRole(roleId){
    //编辑角色验证
    editRoleValidator();
    $("#hidRoleId").val(roleId);
    // PostForm("/cwp/front/sh/role!execute", "uid=c006","", updateOneMenuResultArrived, '',"frmMain");//得到用户权限一级菜单-web
    // PostForm("/cwp/front/sh/appMenu!execute", "uid=appmenu008","", appUpdateOneMenuResultArrived, '',"frmMain");//得到用户权限一级菜单-app
    // PostForm("/cwp/front/sh/role!execute", "uid=c005","", updateMenuResultArrived, '',"frmMain");//角色名称和描述
    $.getJSON('/cwp/src/json/role/role_c006.json',function(data){
        updateOneMenuResultArrived(data);
    })
    $.getJSON('/cwp/src/json/role/role_appMenu_appmenu008.json',function(data){
        appUpdateOneMenuResultArrived(data);
    })
    $.getJSON('/cwp/src/json/role/role_c005.json',function(data){
        updateMenuResultArrived(data);
    })
    $("#modalAddRole").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal');
}
//修改角色名称和描述
function updateMenuResultArrived(result){
    $(".tipArea div").html("").attr("class","");
    $('#roleName').val(result.bean.roleName);
    $("#oldRoleName").val(result.bean.roleName);
    $("#roleName")[0].readOnly=true;
    $('#addRoleDescrebe').val(result.bean.describeRole);
    $("#exampleModalLabel").text("修改角色");
}

//填充树状结构图-web
function updateOneMenuResultArrived(result){
    var treeObj = $.fn.zTree.getZTreeObj("treeOrg");//根据 treeId 获取 zTree 对象
    treeObj.checkAllNodes(false);//清空树状结构图
    var chd="";
    for(var i=0;i<result.beans.length;i++){
        chd=treeObj.getNodeByParam("powerId", result.beans[i].menuId, null);
        //判断是否存在子节点
        if(chd){
            if("children" in chd){
                chd.open=true;
            }else{
                treeObj.checkNode(treeObj.getNodeByParam("powerId", result.beans[i].menuId, null), true, true);//遍历选择树状权权限
            }
        }
    }
}
//填充树状结构图-app
function appUpdateOneMenuResultArrived(result){
    var treeObj = $.fn.zTree.getZTreeObj("treeOrg2");//根据 treeId 获取 zTree 对象
    treeObj.checkAllNodes(false);//清空树状结构图
    var chd="";
    for(var i=0;i<result.beans.length;i++){
        chd=treeObj.getNodeByParam("id", result.beans[i].buttonId, null);
        //判断是否存在子节点
        if(chd){
            if("children" in chd){
                chd.open=true;
            }else{
                treeObj.checkNode(treeObj.getNodeByParam("id", result.beans[i].buttonId, null), true, true);//遍历选择树状权权限
            }
        }
    }
}


//查询所有部门

// var strzTree =  "[";

var strzTreeResult;


function initWebTree(){
    // PostForm("/cwp/front/sh/role!execute", "uid=c003", "", getDeptTree1, '');
    $.getJSON('/cwp/src/json/role/role_c003.json',function(data){
        getDeptTree1(data);
    })
}
//获取web树形数据
function getDeptTree1(result){
    // for(var i=0;i<result.beans.length;i++){
    //     strzTree += '{"name":"'+result.beans[i].description +'","powerId":"'+result.beans[i].id+'","id":"'+result.beans[i].sortNumber+'","pId":"'+result.beans[i].parentId+'"},';
    // }
    strzTreeResult = result;
    // PostForm("/cwp/front/sh/role!execute", "uid=c002", "", getDeptTree, '');
    $.getJSON('/cwp/src/json/role/role_c002.json',function(data){
        getDeptTree(data);
    })
}

//获取数据初始化部门树-web
function getDeptTree(result){
    if(result.returnCode=="0"){

        // 合并组织树数据
        var strzTreeResultFull = result.beans.concat( strzTreeResult.beans );
        var strzTreeData1 = [];
        var strzTreeData2 = [];
        // 拆分组织树
        for(var i=0;i<strzTreeResultFull.length;i++){
            if(strzTreeResultFull[i].sortNumber.length == 4){
                strzTreeResultFull[i].sortNumberParent = '0';
                strzTreeData1.push(strzTreeResultFull[i]);
            }else{
                strzTreeResultFull[i].sortNumberParent = String(strzTreeResultFull[i].sortNumber.slice(0,(strzTreeResultFull[i].sortNumber.length-2)));
                strzTreeData2.push(strzTreeResultFull[i]);
            }
        }
        var strzTree =  "[";
        for(var i=0;i<strzTreeData1.length;i++){
            strzTree += '{"name":"'+strzTreeData1[i].description +'","id":"'+strzTreeData1[i].sortNumber + '","powerId":"' + strzTreeData1[i].id + '","powerPId":"' + strzTreeData1[i].parentId  + '","pId":"'+strzTreeData1[i].sortNumberParent+'"},';
        }

        //配置组织结构树
        var setting = {
            check: {
                enable: true,
                chkboxType: { "Y": "ps", "N": "ps" }
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            view: {
                showIcon: false
            },
            callback: {
                onClick: zTreeOnClick
            }
        };

        for(var i=0;i<strzTreeData2.length;i++){
            if(i==strzTreeData2.length-1){
                strzTree += '{"name":"'+strzTreeData2[i].description +'","powerId":"'+strzTreeData2[i].id+'","id":"'+strzTreeData2[i].sortNumber + '","powerPId":"' + strzTreeData2[i].parentId  + '","pId":"'+strzTreeData2[i].sortNumberParent+'"}';
                break;
            }
            strzTree += '{"name":"'+strzTreeData2[i].description +'","powerId":"'+strzTreeData2[i].id+'","id":"'+strzTreeData2[i].sortNumber + '","powerPId":"' + strzTreeData2[i].parentId  + '","pId":"'+strzTreeData2[i].sortNumberParent+'"},';
        }

        strzTree +="]";
        var zNodes=JSON.parse(strzTree);
        $.fn.zTree.init($("#treeOrg"), setting, zNodes );

    }
}
//获取APP树形数据
function initAppTree() {
    // PostForm("/cwp/front/sh/appMenu!execute", "uid=appmenu003", "", function (result){
    //     switch (result.returnCode) {
    //         case "0":
    //             $("#dataTreeTotal").text("共" + result.beans.length + "条记录");
    //             if (result.beans.length > 0) {
    //                 //渲染树对象数据
    //                 constructTree(result.beans);
    //             }
    //             break;
    //         case "1":
    //             tipModal("icon-cross", "暂无配置菜单数据");
    //             break;
    //         case "-9999":
    //             tipModal("icon-cross", "菜单树获取失败");
    //             break;
    //         default:
    //             break;
    //     }
    // }, '', '');

    $.getJSON('/cwp/src/json/role/appMenu_appmenu003.json',function(result){
        switch (result.returnCode) {
            case "0":
                $("#dataTreeTotal").text("共" + result.beans.length + "条记录");
                if (result.beans.length > 0) {
                    //渲染树对象数据
                    constructTree(result.beans);
                }
                break;
            case "1":
                tipModal("icon-cross", "暂无配置菜单数据");
                break;
            case "-9999":
                tipModal("icon-cross", "菜单树获取失败");
                break;
            default:
                break;
        }
    })
}
//渲染APP树对象数据
function constructTree(data) {
    // 根据sortNumber从小到大排序
    data.sort(function(a,b){return Number(a.sortNumber)-Number(b.sortNumber)});
    var zNodes = [];
    for (var i = 0; i < data.length; i++) {
        // 增加排序父ID
        if (data[i].sortNumber.length == 4) {
            data[i].sortNumberParent = '0';
        } else {
            data[i].sortNumberParent = String(data[i].sortNumber.slice(0, (data[i].sortNumber.length - 2)));
        }

        var obj = new Object();
        //id / pId 表示节点的父子包含关系
        obj.ztreeId=Number(data[i].sortNumber);
        obj.pId=Number(data[i].sortNumberParent);
        obj.name = data[i].name;//菜单名称
        obj.sortNumber = data[i].sortNumber;//排序号
        obj.parentId = data[i].sortNumberParent;//父级排序号
        obj.id = data[i].id;//菜单id
        // obj.url = data[i].url;//菜单对应的链接
        // obj.icon = data[i].icon;//菜单对应的图标
        zNodes.push(obj);
    }
    //配置组织结构树
    var setting = {
        check: {
            enable: true,
            chkboxType: { "Y": "ps", "N": "ps" }
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "ztreeId",
                pIdKey: "pId"
            }
        },
        view: {
            showIcon: false
        },
        callback: {
            onClick: appZTreeOnClick
        }
    };
    $.fn.zTree.init($("#treeOrg2"), setting, zNodes);
};
//web部门选择
function zTreeOnClick(event, treeId, treeNode) {
    var treeObj = $.fn.zTree.getZTreeObj("treeOrg");
    var nodes = treeObj.getCheckedNodes(true);
    for(var i= 0;i<nodes.length;i++){
        brr[i] = nodes[i].powerId;
    }
}
//APP部门选择
function appZTreeOnClick(event, treeId, treeNode) {
    var treeObj = $.fn.zTree.getZTreeObj("treeOrg2");
    var nodes = treeObj.getCheckedNodes(true);
    for(var i= 0;i<nodes.length;i++){
        appBrr[i] = nodes[i].id;
    }
}


//显示欲编辑部门信息
// function getDeptbyId(result){
//     if(result.returnCode=="0"){
//         displayDeptModal();
//         $("#hidModalDeptId").val(result.object.deptId);
//         $("#hidDeptPId").val(result.object.parentId);
//         $("#deptName").val(result.object.deptName);
//         $("#type").val(result.object.type);
//         $("#orderNum").val(result.object.orderNum);
//         $("#modalAddDeptTitle").html("编辑部门");
//     }
//     else if(result.returnCode=="-9999"){
//         tipModal('icon-cross',"获取部门信息失败");
//     }
//     else{
//         tipModal('icon-cross',result.returnMessage);
//     }
// }


$('#treeOrg,#treeOrg2').slimScroll({
    width: 'auto', //可滚动区域宽度
    height: '305px', //可滚动区域高度
    size: '5px' //组件宽度
});

